package org.tc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tc.common.Result;
import org.tc.bean.User;
import org.tc.common.ResultUtils;
import org.tc.exception.CustomException;
import org.tc.service.UserService;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zxd on 2018/1/31.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private Logger LOGGER= LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ResponseEntity<Result> register(@Valid  User user, BindingResult bindingResult) throws CustomException {
        //校验
        //判断是否有错误
        if(bindingResult.hasErrors()){
            //获取错误信息返回给调用者
            List<ObjectError> errors = bindingResult.getAllErrors();
            List<String> list=new ArrayList<>();
            for (ObjectError error:errors) {
                //获取每一个错误信息
                String msg = error.getDefaultMessage();
                LOGGER.info("错误信息{}.",msg);
                list.add(msg);
            }
            String message= org.apache.commons.lang3.StringUtils.join(list,",");
            return ResponseEntity.ok(ResultUtils.buildFail(100,message));
        }

        //注册
        userService.register(user);
        return ResponseEntity.ok(ResultUtils.buildSuccess());
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseEntity<Result> login(String username,String password) throws CustomException {
        LOGGER.debug("当前登录的用户为{},",username);
        if(StringUtils.isEmpty(username)){
            return ResponseEntity.ok(ResultUtils.buildFail(101,"用户名不能为空!"));
        }
        if(StringUtils.isEmpty(password)){
            return ResponseEntity.ok(ResultUtils.buildFail(102,"密码不能为空!"));
        }
        String token=userService.login(username,password);
        if(StringUtils.isEmpty(token)){
            LOGGER.debug("用户{}登录失败",username);
            return ResponseEntity.ok(ResultUtils.buildFail(103,"登录失败!"));
        }
        LOGGER.debug("用户{},登录的token为{}",username,token);
        return ResponseEntity.ok(ResultUtils.buildSuccess(token));
    }


    @RequestMapping(value = "/{token}",method = RequestMethod.POST)
    public ResponseEntity<Result> queryUserByToken(@PathVariable("token") String token) throws CustomException {
        LOGGER.debug("当前查询登录信息的用户为{},",token);
        User user = userService.queryUserByToken(token);
        if(user==null){
            LOGGER.debug("用户时效!token为{}",token);
            return ResponseEntity.ok(ResultUtils.buildFail(105,"登录失效!"));
        }
        return ResponseEntity.ok(ResultUtils.buildSuccess(user));
    }


    @RequestMapping("/loginByPhone")
    public ResponseEntity<Result> loginByPhone(String phoneNumber,String smscode) throws CustomException {
        String token= userService.loginByPhone(phoneNumber,smscode);
        if(StringUtils.isEmpty(token)){
            LOGGER.debug("用户{}登录失败",phoneNumber);
            return ResponseEntity.ok(ResultUtils.buildFail(103,"登录失败!"));
        }
        LOGGER.debug("用户{},登录的token为{}",phoneNumber,token);
        return ResponseEntity.ok(ResultUtils.buildSuccess(token));
    }



    /**
     * @param param
     * @param type  1,2,3分别代表 username、phone、email
     * @return
     */
    @RequestMapping("/check/{param}/{type}")
    @ResponseBody
    public Result<Boolean> check(@PathVariable("param")String param,@PathVariable("type") Integer type){
        LOGGER.debug("the param is {},and type is{}",param,type);
        Boolean result=userService.check(param,type);
        return ResultUtils.buildSuccess(result);
    }



}
